#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <signal.h>

#define ARGC 20

/*
 Just need to free the memory after
 the first run through, then all set.
 */

/*
 * Provides the split functionality on an array of chars.
 * @param baseString the char array that needs to be parsed
 * @param returnString the results are stored in this char* array
 * @return 1 if the last argument was a '&', else 0
*/
int split(char baseString[], char* returnString[], int* totalArgs){

	int base = 0;
	int total = 0;

	int i = 0;
	while(baseString[i] != 0){                                      //for every letter in the str

	if(baseString[i] == ' ' || baseString[i] == '\n'){            //if we get to a space

		char* newstr = calloc((i-base+1),sizeof(char));            //make a new str
		int k = 0;
		for( ; base < i ; base++){                                //add each char to a new str
			newstr[k] = baseString[base];
			k++;
		}
			newstr[k] = '\0';               	                          //null terminate the string

			returnString[total] = newstr;                             //add newstr to the final list
			total++;                                                   //inc the tracker var for it
			base = i;                                                  //reset the base of baseString
			base++;
		}

		i++;

	}
	returnString[total] = NULL;			                          //null terminate the array of params


	*totalArgs = total;

	if(returnString[total-1][0]=='&'){
		returnString[total-1] = NULL;
		return 1;
	}

	return 0;
}

/*
 * frees memory from a char* array
 * @param size The size of the array. An array of
 * size 2 will have index 0 and 1 freed.
 * @param array The array to free memory from
*/
void wipe(int size, char* array[]){
	int i;
	for(i = 0; i < size; i++){
		free(array[i]);
	}
}

int shell(int argc, char* argv[]){

	pid_t pid;

	char input[256];			//stdin placed here
	char* args[ARGC];			//args to pass to main
	int background;
	int* total = malloc(sizeof(int));
	*total = 0;

	while(1){

	printf("$ ");
	if (!fgets(input, 255, stdin)){
		printf("could not read");
	}

	wipe(*total,args);
	background = split(input, args, total);                    //parse params


	if( !strcmp(args[0],"exit") ){
		break;
	}

	pid = fork();
	if(!pid){                    //child
		if(background){
			fclose(stdout);		//close stdout if backgrounding
			fclose(stdin);
		}
		execvp(args[0], args);
	}
	else{
		if(!background){
		wait(0);
		}
	}


	}

	return 0;
}
